package com.zp.mall.product.exception;

import com.zp.common.exception.BizCodeEnum;
import com.zp.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangpeng
 * @create 2020/11/1 14:02
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.zp.mall.product.controller")
@RestControllerAdvice(basePackages = "com.zp.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e){
//        log.error ("异常信息：{}，异常类：{}", e.getMessage (), e.getClass ());
        BindingResult result = e.getBindingResult ();
        Map<String, String> errMap = new HashMap<> ();
        List<FieldError> fieldErrors = result.getFieldErrors ();
        fieldErrors.forEach (item -> {
            errMap.put (item.getField (), item.getDefaultMessage ());
        });
        return R.error (BizCodeEnum.VALID_EXCEPTION.getCode (), BizCodeEnum.VALID_EXCEPTION.getMsg ()).put ("data", errMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        return R.error (BizCodeEnum.UNKNOW_EXCEPTION.getCode (), BizCodeEnum.UNKNOW_EXCEPTION.getMsg ());
    }
}
